import { serverApi } from "./config";
import { sendSms } from "./testSendSms";
import { testUpload } from "./testUpload";
import { recognizeBusinessLicense } from "./testOcr";

// 定义请求数据结构（对应 TraderShopDTO 结构体）
interface TraderShopDTO {
  entryType: string;
  companyName: string;
  contactPerson: string;
  phone: string;
  password: string;
  province: string;
  city: string;
  district: string;
  address: string;
  industry: string;
  businessScope: string;
  companySize: string;
  registeredCapital: number;
  establishmentDate: string; // 格式：yyyy-MM-dd
  businessLicense: string; // URL
  creditCode: string;
  companyType: string;
  legalPerson: string;
  smsCode: string; // 短信验证码
  shopMode: "SUPPLIER" | "COMMON"; //新增的两个字段
}

// 定义接口返回结果结构（假设后端返回的 Result 格式）
interface ApiResult<T = any> {
  code: number;
  msg: string;
  data: T;
}

// 测试用请求地址
const url = `${serverApi}/gruul-mall-shop/shop-api/open-register-shop`;

// 模拟请求数据（严格遵循 TraderShopDTO 类型约束）
const shopData: TraderShopDTO = {
  entryType: "international_trader",
  companyName: "测试贸易有限公司",
  contactPerson: "张三",
  phone: "13800138001",
  password: "Test@123456",
  province: "广东省",
  city: "深圳市",
  district: "南山区",
  address: "科技园南区100号",
  industry: "electronics",
  businessScope: "电子产品销售、技术服务",
  companySize: "10-50",
  registeredCapital: 1000000.0,
  establishmentDate: "2020-01-15",
  businessLicense: "https://example.com/license.jpg",
  creditCode: "91440300MA5EXAMPLE",
  companyType: "limited_liability",
  legalPerson: "李四",
  smsCode: "50505",
  shopMode: "SUPPLIER",
};

/**
 * 发送店铺注册请求
 * @param data 注册表单数据（TraderShopDTO 类型）
 * @returns Promise<ApiResult> 接口返回结果
 */
async function registerShop(data: TraderShopDTO): Promise<ApiResult> {
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        // 如需认证，添加Token头
        // 'Authorization': 'Bearer your_test_token'
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error(`请求失败，状态码: ${response.status}`);
    }

    // 解析响应并指定类型为 ApiResult
    const result: ApiResult = await response.json();
    return result;
  } catch (error) {
    console.error(
      "请求或处理失败:",
      error instanceof Error ? error.message : String(error)
    );
    throw error; // 抛出错误供外部处理
  }
}

// 执行注册请求并处理结果
async function testRegister() {
  try {
    console.log("--------- 开启上传 ----------------");
    const uploadPath = await testUpload();
    await recognizeBusinessLicense(uploadPath);
    shopData.businessLicense = uploadPath;
    console.log("--------- 发送短信 ----------------");
    const smsCode = await sendSms(shopData.phone);
    if (sendSms == null) throw `短信发送失败!`;
    shopData.smsCode = smsCode as string;
    console.log("--------- 注册企业 ----------------");
    const result = await registerShop(shopData);
    console.log("接口返回成功:", result);
    console.log("状态码:", result.code);
    console.log("消息:", result.msg);
    console.log("返回数据:", result.data);
  } catch (error) {
    console.error("注册失败:", error);
  }
}

// 调用测试函数
testRegister();
